const oracledb = require('oracledb');
const logHandler = require('../component/logHandler');
const OracleConfig = require('../config/OracleConfig');

module.exports = {

  /**
   * 执行sql
   */
  executeSql: function (sql, callback) {
    let _this = this;
    // 连接数据库
    oracledb.getConnection(OracleConfig.ORACLE_CONNECTION_INFO, function (err, connection) {
      if (err) {
        logHandler.error(err.message);
        return;
      } else {
        logHandler.log("连接成功");
      }
      // 执行sql
      let _connection = connection;
      connection.execute(sql, [], function (err, result) {
        if (err) {
          logHandler.error(err.message);
          doRelease(_connection);
          return;
        }
        // 回调函数
        callback(result.rows.map((v) => {
          return result.metaData.reduce((p, key, i) => {
            p[key.name] = v[i];
            return p;
          }, {})
        }));
        doRelease(_connection);
      });
    }
    );
  },


  /**
   * 从oracle数据库的mdl_stock_analysis表中查找date_字段最大值
   */
  findMaxDateOfMdlStockAnalysis: function () {
    let sql = `select max(t.date_) maxDate from mdl_stock_analysis t`;
    return new Promise((resolve, reject) => {
      this.executeSql(sql, function (result) {
        if (!result) {
          logHandler.warn('连接oracle数据库出错');
          reject(result);
        }
        if (result.length == 0) {
          logHandler.info('没有符合条件的数据');
          reject(result);
        }
        resolve(result[0].MAXDATE);
      });
    });
  },

  /**
   * 从oracle中，根据date，返回mdl_stock_analysis表中的记录
   * @param {*} date 
   */
  findMdlStockAnalysisByDate: function (date) {
    let sql = `select * from mdl_stock_analysis t where t.date_=to_date('${date}','yyyy-mm-dd')`;
    return new Promise((resolve, reject) => {
      this.executeSql(sql, function (result) {
        if (!result) {
          logHandler.warn('连接oracle数据库出错');
          reject(result);
        }
        if (result.length == 0) {
          logHandler.info('没有符合条件的数据');
          reject(result);
        }
        resolve(result);
      });
    });
  }
};

/**
 * 关闭数据库连接
 * @param {*} connection 
 */
function doRelease(connection) {
  connection.close(
    function (err) {
      if (err)
        logHandler.error(err.message);
    }
  );
}

